package cn.itcast.consumer.web;


import cn.itcast.consumer.pojo.User;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.Ribbon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;


@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;
//    @Autowired
//    private RibbonLoadBalancerClient client;
    @Autowired
    private DiscoveryClient discoveryClient;


    //现在的代码用作测试 熔断
    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdFallback")
    public String queryById(@PathVariable("id") Long id) {

        String url = "http://user-service/user" + id;
       String user = restTemplate.getForObject(url,String.class);
        return user;
    }
    //熔断失败后，返回一个友好的错误提示信息
    public String queryByIdFallback(Long id){

        return "不好意思，服务器太拥挤!";
    }






    //这是原始的代码
//    @GetMapping("{id}")
//    public User queryById(@PathVariable("id") Long id) {
//
////        //  根据服务id获取实例
////        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
////
////        //从实例中获取ip和端口
////        ServiceInstance instance = instances.get(0);
//
////        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/user/" + id;
//
//        String url = "http://user-service/user" + id;
//        User user = restTemplate.getForObject(url, User.class);
//        return user;
//    }
}
